package com.liush.system.filter;

import com.liush.common.helper.JwtHelper;
import com.liush.common.result.Result;
import com.liush.common.result.ResultCodeEnum;
import com.liush.common.util.ResponseUtil;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collection;
import java.util.Collections;

/**
 * @Author: liush
 * @CreateTime: 2023-03-05  11:43
 * @Description: 认证解析token过滤器
 */
public class TokenAuthenticationFilter extends OncePerRequestFilter {

    private RedisTemplate redisTemplate;

    public TokenAuthenticationFilter(RedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    //所有请求的必经之路
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //请求路径
        String requestURI = request.getRequestURI();
        //登录
        if ("/admin/system/index/login".equals(requestURI)) {
            filterChain.doFilter(request, response);//放行
            return;
        }
        //获取token信息 判断是不是一个认证的用户
        String token = request.getHeader("token");
        if (!StringUtils.isEmpty(token)) {
            String username = JwtHelper.getUsername(token);
            if (!StringUtils.isEmpty(username)) {
                //从redis获取用户对应的权限集合
                Collection<GrantedAuthority> authorities = (Collection<GrantedAuthority>) redisTemplate.boundValueOps(username).get();
                //把认证成功的用户对象放到上下文对象中
                Authentication authentication = new UsernamePasswordAuthenticationToken(username, null, authorities);
                SecurityContextHolder.getContext().setAuthentication(authentication);
                //如果是一个合法的用 就放行
                filterChain.doFilter(request, response);//放行
            }
        } else {
            ResponseUtil.out(response, Result.fail("您不是一个有效的用户!!"));
        }

    }
}
